package com.jron.cqiu.kernel.cmdline;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.lang.ArrayUtils;
import com.jron.cqiu.kernel.scheduler.IKingTrigger;
import com.jron.cqiu.kernel.mail.IMailOrder;
import com.jron.cqiu.util.Message;

import java.io.PrintWriter;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-23
 * @Time: 15:50:17
 */
public class CommandLineListener implements ICommandLineListener, IDefined, Message {

    //private static Log log = LogFactory.getLog(CommandLineListener.class);

    IKingCommand ikc = IKingCommand.INSTANCE;

    public int cmdEntered(PrintWriter pw, String... command) {

        CommandLineParser parser = new BasicParser();
        CommandLine cl = null;
        try {
            int prefix = ArrayUtils.indexOf(command, IKingCommand.USAGE_PREFIX);
            if (prefix == 0) command = (String[]) ArrayUtils.remove(command, prefix);
            else return CONTINUE_READING;

            cl = parser.parse(ikc.kingOptions(), command);

            if (cl.hasOption(help)) ikc.help();

            if (cl.hasOption(quit)) return STOP_READING;

            if (cl.hasOption(runningKing)) {
                IKingTrigger.INSTANCE.run();
                return GOON_BUT_STOP_READING;
            }

            if (cl.hasOption(mailOrder)) {
                String oFrom = cl.getOptionValue(mailOrder);
                if (!oFrom.matches(EMAIL_REGEX)) {
                    pw.println(invalid_email_msg.message(oFrom));
                    return CONTINUE_READING;
                }

                StringBuffer o = new StringBuffer("{ ");
                for (String s : cl.getArgs()) o.append(s).append(" ");
                o.append("}");
                pw.println("The mail order is: " + o.toString());
                IMailOrder.INSTANCE.sendOrder(o.toString(), oFrom);
            }

            if (cl.hasOption(kingHelp)) {
                String to = cl.getOptionValue(kingHelp);
                if (to.matches(EMAIL_REGEX)) {
                    IMailOrder.INSTANCE.sendHelp(to);
                    pw.println("A king help of mail order have been sent to " + to);
                } else pw.println(invalid_email_msg.message(to));
            }

        } catch (ParseException e) {
            pw.println(e.getMessage());
            ikc.help();
        }

        return CONTINUE_READING;
    }
}
